const _ = require('lodash');
const moment = require("moment");
//moment.tz.setDefault('Asia/Shanghai')
module.exports = class {
    constructor(app) {
        this.app = app;

        this.subDeviceData = data => {
            data && this.onData(data);
            return 'ok';
        };
        this.app.eventBus.on('HTTP_DATA_RECEVED', this.subDeviceData);
    }

    async onData(data) {
        const {topic, payload} = data;
        if (topic.match('/databack')) {

            this.app.eventBus.emit("MQTT_DATA_RECEVED", data);

            const {deviceName, status} = payload;
            const deviceId = topic.replace('/databack', '');
            const realData = await this.app.model['DeviceRealData'].findOne({deviceId}, null);
            if (realData && _.isEqual(realData.points, payload)) {
                console.log('return')
                return false;
            }
            console.log('save', deviceId);
            const dataRealData = {points: {...payload}, deviceName, deviceId, status}
            const now = new Date().getTime();
            dataRealData.createdAt = new Date(now + 8 * 60 * 60 * 1000);
            if (!realData) {
                await this.app.model['DeviceRealData'](dataRealData).save();
                const model = {logType: 'report', topic, payload, deviceId, deviceName, status};
                this.app.model['BLog'](model)
                    .save();
                return true
            }

            const {createdAt} = realData;
            const saveDataTs = moment(createdAt).valueOf();
            const ts = moment().valueOf();
            if ((ts - saveDataTs) < 500) {
                console.log('s - saveDataTs) < 500', ts)
                console.log('s - saveDataTs) < 500', saveDataTs)
                console.log('s - saveDataTs) < 500', ts - saveDataTs)

                return false;
            }

            await this.app.model['DeviceRealData'].updateOne({deviceId}, dataRealData)
            const model = {logType: 'report', topic, payload, deviceId, deviceName, status};
            this.app.model['BLog'](model)
                .save();
            return true;
        }
        if (topic.match('/ctrlReport')) {
            var deviceId = topic.replace('/ctrlReport', '');
            const model = {logType: 'ctrl', topic, payload, deviceId};
            console.log(model);
            this.app.model['BLog'](model)
                .save();
            return true
        }
        return false;
    }

    async destroy() {
        this.app.eventBus.removeListener(this.httpBus, this.subDeviceData);

        return 'ok';
    }


}
